package com.example.ota_ble

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.content.BroadcastReceiver
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.Uri
import android.os.Bundle
import android.provider.OpenableColumns
import android.text.Editable
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts

import androidx.appcompat.app.AppCompatActivity

import com.example.ota_ble.ble.connect.buletoothGattManage
import com.example.ota_ble.ble.dataWrite.ble_write_thread

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.UUID

@SuppressLint("RestrictedApi","MissingPermission")
class otaactivity : AppCompatActivity() {
     val TAG = "rocjan.otaactivity"

    /*  连接操作
    * */
    lateinit var bluetoothAdapter: BluetoothAdapter   //sys
    lateinit var bluetoothGattMg:  buletoothGattManage //user
    lateinit var bluetoothGatter:  BluetoothGatt //user
    lateinit var bluetoothDev : BluetoothDevice //user
    /*
    *   组件
    * **/
    lateinit var ota_id_radioGroup:RadioGroup
    lateinit var ota_id_ble:RadioButton
    lateinit var ota_id_mcu:RadioButton
    lateinit var ota_id_btn_edittext:EditText
    lateinit var ota_id_btn_openfile:Button
    lateinit var ota_id_btn_up:Button
    lateinit var ota_id_tempinal:TextView

    //
    lateinit var select_uri:Uri
    val openFolderRequestCode = 1
    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_ota)
        var ble_addr = intent.getStringExtra("BLE_ADDR")
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

        /**
         * 获取蓝牙设备
         * */
        bluetoothDev = bluetoothAdapter?.getRemoteDevice(ble_addr)!!
        if((bluetoothDev)==null)
        {
            onBackPressed()
        }


        this.bluetoothGattMg = buletoothGattManage()
        this.bluetoothGattMg.blueGatt=bluetoothDev.connectGatt(this,false,this.bluetoothGattMg.get_gattRecall())

        // 注销广播接收器

        /**
         * 组件初始化
         * */
        ota_id_radioGroup    =  findViewById<RadioGroup>(R.id.ota_id_radioGroup)
        ota_id_ble     =  findViewById<RadioButton>(R.id.ota_id_ble)
        ota_id_mcu    =  findViewById<RadioButton>(R.id.ota_id_mcu)
        ota_id_btn_edittext    =  findViewById<EditText>(R.id.ota_id_btn_edittext)
        ota_id_btn_openfile    =  findViewById<Button>(R.id.ota_id_btn_openfile)
        ota_id_btn_up           =  findViewById<Button>(R.id.ota_id_btn_up)
        ota_id_tempinal =  findViewById<TextView>(R.id.ota_id_tempinal)
        globbal_calss.register_tempinal(ota_id_tempinal)
        this.ota_id_btn_edittext.isEnabled = false

        // 打开文件夹，主要获取uri
        this.ota_id_btn_openfile.setOnClickListener {
            openFolder()
        }


         var blet :ble_write_thread = ble_write_thread(this)

        // 打开文件夹，主要获取uri
        this.ota_id_btn_up.setOnClickListener {
            // 执行升级蓝牙固件的功能
             if(ota_id_ble.isChecked)
             {
                 blet.pre_init(this.select_uri,this.bluetoothGattMg,80)
                 blet.run()
             }
            // 执行升级mcu固件的功能
            if(ota_id_mcu.isChecked)
            {
                blet.pre_init(this.select_uri,this.bluetoothGattMg,220)
                blet.run_mcu_ota()
            }
        }
    }


    // 打开文件夹的功能
    private fun openFolder() {

        val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
            // 可选择是否允许返回子目录路径
            type = "*/*" // 允许选择任何类型的文件
            putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
        }
        openDocumentTreeLauncher.launch(intent)
    }
    // 使用 registerForActivityResult 注册启动文件选择器的请求
    private val openDocumentTreeLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                // 用户选择了文件夹
                val uri: Uri? = result.data?.data
                uri?.let {
                    // 你可以在这里处理获取到的文件夹 URI
                    // 比如读取该文件夹内容等
                    Log.i(TAG,"选择的文件夹 URI: $it")

                    this.select_uri = uri
                }
                this.ota_id_btn_edittext.setText(getFileNameFromUri(uri!!))
            }
        }
    fun getFileNameFromUri(uri: Uri): String? {
        var fileName: String? = null
        // 使用 ContentResolver 查询 Uri
        val cursor = contentResolver.query(uri, null, null, null, null)
        cursor?.let {
            if (it.moveToFirst()) {
                // 获取文件名所在列的索引
                val nameIndex = it.getColumnIndex(OpenableColumns.DISPLAY_NAME)
                if (nameIndex != -1) {
                    fileName = it.getString(nameIndex)
                }
            }
            it.close()
        }
        return fileName
    }
}



/*
*       组件初始化
* */

